axios.interceptors.request.use(function (config) {
    let token = localStorage.getItem("token");
    if (token != null) {
        config.headers.Authorization = token;
    }

    return config;
}, function (error) {
    return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
    if (("code" in response.data) && response.data.code > 0) {
        if (response.data.code == 2) {
            window.location.href = generateUrl("/user/login.html", {from: window.location.href})
        }
        console.log("error", response.data);
        alert(response.data.message);
    } else {
        console.log("success", response.data);
    }
    return response;
}, function (error) {
    console.log("exception", error);
    return Promise.reject(error);
});

function generateUrl(path, params, host = "") {
    let url;
    if (host == "") {
        url = new URL(window.location.protocol + "//" + window.location.host + path);
    } else if (host == "-") {
        url = new URL(path);
    } else {
        url = new URL(host + path);
    }

    for (let key in params) {
        if (params[key] == null) {
            continue;
        }
        url.searchParams.append(key, params[key]);
    }

    return url.href;
}

function getParam(name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }

    return null;
}

function buildParams(keys) {
    let params = {};
    for (let i = 0; i < keys.length; ++i) {
        let value = getParam(keys[i]);
        if (value == null) {
            continue;
        }
        params[keys[i]] = value;

    }

    return params;
}

function getLeft(total, extras) {
    if (extras.length == 0) {
        return total;
    }

    let sum = 0;
    for (let i = 0; i < extras.length; ++i) {
        sum += parseInt(extras[i].value);

    }

    return total - sum;
}